package com.zn.task;

import com.netflix.discovery.converters.Auto;
import com.zn.entity.AgencyBusiness;
import com.zn.mapper.AgencyBusinessMapper;
import com.zn.socket.SocketHandler;
import com.zn.util.Constant;
import com.zn.util.DateUtils;
import com.zn.web.rpc.TradeRemoteCall;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by yinjiawei on 2018/7/12.
 */
@Component
public class ListenerSocketState {
    private static final Logger LOGGER = LoggerFactory.getLogger(ListenerSocketState.class);
    @Value("${trade.socket.host}")
    private String host;
    @Value("${trade.socket.port}")
    private String port;
    @Autowired
    private TradeRemoteCall tradeRemoteCall;
    @Autowired
    private AgencyBusinessMapper agencyBusinessMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Scheduled(cron="*/5 * * * * ?")   //每5秒执行一次
    public void task(){
        try{
            SocketHandler socketHandler=SocketHandler.getInstance(host,Integer.valueOf(port));
            LOGGER.warn("connection ----> host" + host+"----> port "+port);
            boolean isClose=socketHandler.isServerClose();
            String isCloseStr=isClose==true?"关闭":"开启";
            LOGGER.info("socket是否关闭................." + isCloseStr);
            //如果是关闭的 需要重连
            if(isClose){
                sendStatus(1);
                SocketHandler.setEmpty();
                SocketHandler.getInstance(host,Integer.valueOf(port));
            }else{
                sendStatus(0);
            }
        }catch (Exception e){
            sendStatus(1);
            LOGGER.error("ListenerSocketState Error ..............:" + e);
        }
    }

    private void sendStatus(Integer socketStatus){
        try {
            String uniqueIdentification=redisTemplate.opsForValue().get(Constant.BUSINESSUNIQUE);
            if(StringUtils.isBlank(uniqueIdentification)){
                //查询一级平台的唯一识别号
                AgencyBusiness agencyBusiness=agencyBusinessMapper.selectByBusinessLevel();
                uniqueIdentification=agencyBusiness.getUniqueIdentification();
                System.err.println("set 唯一识别号....."+uniqueIdentification);
                redisTemplate.opsForValue().set(Constant.BUSINESSUNIQUE,uniqueIdentification);
            }
            tradeRemoteCall.sendSocketStatus(uniqueIdentification,0,socketStatus);
        }catch (Exception e){
            LOGGER.error("sendStatus...."+e);
        }

    }
}
